import React, { useMemo, useRef, useState, useEffect } from 'react';
import { View, StyleSheet, Switch } from 'react-native';
import {
    Layout,
    UI,
    useThemeColors,
    useLocalization,
    LocalizationService,
    useI18n,
    I18nService,
} from '@gaozh1024/rn-toolkit';

const LocalizationTestScreen: React.FC = () => {
    const colors = useThemeColors();
    const styles = StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 12 },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
        rtlBox: { height: 36, minWidth: 100, borderWidth: 1, borderColor: colors.border, borderRadius: 8, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 12 },
    });

    // hook: localization 信息 + 刷新
    const { info, refresh } = useLocalization();

    // ========= 新增：i18n（翻译）功能测试 =========
    const { t, tag, mode, rtl, setLanguageMode, setLanguageTag, updateOverrides, resetOverrides } = useI18n();

    // 注册示例语言包（页面演示用）
    useEffect(() => {
        I18nService.registerPacks([
            {
                tag: 'en-US',
                messages: {
                    'title.test': 'I18n Test Page',
                    'welcome': 'Welcome, {{name}}!',
                    'system.default': 'System default (en-US)',
                    'common.ok': 'OK',
                },
            },
            {
                tag: 'zh-CN',
                aliases: ['zh', 'zh-hans'],
                messages: {
                    'title.test': '语言测试页',
                    'welcome': '欢迎，{{name}}！',
                },
            },
            {
                tag: 'zh',
                messages: {
                    'common.ok': '确定',
                    'common.cancel': '取消',
                },
            },
            {
                tag: 'ar-SA',
                rtl: true,
                messages: {
                    'title.test': 'صفحة اختبار اللغة',
                    'welcome': 'مرحبًا، {{name}}!',
                    'common.ok': 'موافق',
                },
            },
        ]);
    }, []);

    // 翻译演示：插值与覆盖
    const [nameInput, setNameInput] = useState('小明');
    const [overrideKey, setOverrideKey] = useState('welcome');
    const [overrideValue, setOverrideValue] = useState('');

    const onApplyOverride = () => {
        if (overrideKey.trim().length) {
            updateOverrides({ [overrideKey.trim()]: overrideValue });
        }
    };
    const onResetOverrides = () => {
        resetOverrides();
    };

    const onSetModeSystem = () => setLanguageMode('system');
    const onSetModeFixed = () => setLanguageMode('fixed');

    const onSetTagZhCN = () => setLanguageTag('zh-CN');
    const onSetTagEnUS = () => setLanguageTag('en-US');
    const onSetTagArSA = () => setLanguageTag('ar-SA');
    const onSetTagAliasZhHans = () => setLanguageTag('zh-Hans'); // 别名映射 -> zh-CN
    const onRestoreSystemTag = () => setLanguageTag(null);        // 回到 system 模式

    // service 独立测试状态
    const [serviceInfo, setServiceInfo] = useState<any | null>(null);
    const [subscribe, setSubscribe] = useState<boolean>(false);
    const unsubRef = useRef<null | (() => void)>(null);

    // 最佳语言匹配
    const [langTagsInput, setLangTagsInput] = useState<string>('zh-CN, en-US, fr-FR');
    const langTags = useMemo(
        () => langTagsInput.split(',').map(s => s.trim()).filter(Boolean),
        [langTagsInput],
    );
    const [bestLanguage, setBestLanguage] = useState<{ languageTag: string; isRTL: boolean } | null>(null);

    // 错误提示
    const [lastError, setLastError] = useState<string | null>(null);

    // Hook 刷新
    const onRefreshHook = () => {
        refresh();
    };

    // Service：读取与刷新（带 onError）
    const onGetServiceInfo = () => {
        const res = LocalizationService.getInfo();
        setServiceInfo(res);
    };
    const onRefreshService = () => {
        try {
            const next = LocalizationService.refresh({
                onError: (err: Error) => setLastError(err.message || String(err)),
            });
            setServiceInfo(next);
            setLastError(null);
        } catch (e: any) {
            setLastError(e?.message || String(e));
        }
    };

    // 订阅切换
    const onToggleSubscribe = (val: boolean) => {
        setSubscribe(val);
        if (val) {
            // 添加订阅
            if (!unsubRef.current) {
                unsubRef.current = LocalizationService.addListener((next) => {
                    setServiceInfo(next);
                });
            }
        } else {
            // 取消订阅
            if (unsubRef.current) {
                unsubRef.current();
                unsubRef.current = null;
            }
        }
    };

    // 最佳语言匹配
    const onFindBestLanguage = () => {
        const res = LocalizationService.findBestLanguage(langTags);
        setBestLanguage(res);
    };

    return (
        <Layout.Page
            headerShown
            headerProps={{ title: 'Localization 测试', backVisible: true }}
            padding={16}
            scrollable
            testID="LocalizationTestScreen"
        >
            {/* Hook：信息展示与刷新 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>本地化信息（hook）</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="刷新信息（hook）" onPress={onRefreshHook} testID="localization-btn-refresh-hook" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>Locale：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-languageTag">
                            languageTag：{info?.locale?.languageTag ?? '（未知）'}
                        </UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-languageCode">
                            languageCode：{info?.locale?.languageCode ?? '（未知）'}
                        </UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-countryCode">
                            countryCode：{info?.locale?.countryCode ?? '（未知）'}
                        </UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-isRTL">
                            isRTL：{String(info?.locale?.isRTL ?? '（未知）')}
                        </UI.Text>

                        <UI.Text variant="caption" color="subtext" mt={8} mb={8}>其他：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-timeZone">timeZone：{info?.timeZone ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-currencies">currencies：{info?.currencies?.join(', ') || '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-country">country：{info?.country ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-24h">uses24HourClock：{String(info?.uses24HourClock ?? '（未知）')}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-hook-metric">usesMetricSystem：{String(info?.usesMetricSystem ?? '（未知）')}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* Service：读取与刷新 + 错误回调 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>服务接口</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="读取服务信息" onPress={onGetServiceInfo} testID="localization-btn-service-get" />
                        <UI.Button title="刷新（带 onError）" variant="outline" onPress={onRefreshService} testID="localization-btn-service-refresh" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>最近一次服务信息：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-text-service">
                            {serviceInfo ? JSON.stringify(serviceInfo) : '（空）'}
                        </UI.Text>
                        <UI.Text variant="caption" color="subtext" mt={8} mb={8}>错误：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-text-error">{lastError || '（无）'}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* 订阅变化（addListener） */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>订阅变化</UI.Text>
                    <View style={styles.row}>
                        <UI.Text variant="body2" color="text">开启订阅</UI.Text>
                        <Switch value={subscribe} onValueChange={onToggleSubscribe} testID="localization-switch-subscribe" />
                    </View>
                    <UI.Text variant="caption" color="subtext" mt={8}>说明：系统语言/地区变化时会回调最新信息。</UI.Text>
                </Layout.Card>
            </View>

            {/* 最佳语言匹配 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>最佳语言匹配（findBestLanguage）</UI.Text>
                    <UI.Text children={'候选语言 tags（逗号分隔）'} />
                    <UI.Input
                        value={langTagsInput}
                        onChangeText={setLangTagsInput}
                        placeholder="zh-CN, en-US, fr-FR"
                        testID="localization-input-lang-tags"
                    />
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button title="匹配" onPress={onFindBestLanguage} testID="localization-btn-best-language" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>结果：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="localization-text-best-language">
                            {bestLanguage ? `${bestLanguage.languageTag} (isRTL=${String(bestLanguage.isRTL)})` : '（空）'}
                        </UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* ========= 新增：I18n（翻译）功能测试 ========= */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>I18n 基础信息</UI.Text>
                    <View style={[styles.bordered, { marginTop: 4 }]}>
                        <UI.Text variant="body2" color="text" testID="i18n-mode">mode：{mode}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="i18n-tag">tag：{tag ?? '（未设置，跟随系统）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="i18n-rtl">rtl：{String(rtl)}</UI.Text>
                    </View>
                    <UI.Text variant="caption" color="subtext" mt={8}>说明：mode='system' 将根据系统语言选择最佳包；mode='fixed' 固定在手动设定的 tag。</UI.Text>
                </Layout.Card>
            </View>

            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>翻译函数（t）与插值</UI.Text>
                    <View style={styles.col}>
                        <UI.Text children={'姓名（插值参数 name）'} />
                        <UI.Input
                            value={nameInput}
                            onChangeText={setNameInput}
                            placeholder="例如：小明 / John"
                            testID="i18n-input-name"
                        />
                        <UI.Text variant="body2" color="text" mt={8} testID="i18n-text-welcome">
                            {t('welcome', { name: nameInput })}
                        </UI.Text>

                        <UI.Text variant="caption" color="subtext" mt={8}>{`公用文案（展示回退链：zh-CN -> zh）`}</UI.Text>
                        <View style={styles.row}>
                            <UI.Text variant="body2" color="text" testID="i18n-text-ok">common.ok：{t('common.ok')}</UI.Text>
                            <UI.Text variant="body2" color="text" testID="i18n-text-cancel">common.cancel：{t('common.cancel')}</UI.Text>
                        </View>

                        <UI.Text variant="caption" color="subtext" mt={8}>默认英语回退（当当前语言未包含时）</UI.Text>
                        <UI.Text variant="body2" color="text" testID="i18n-text-default-from-en">
                            system.default：{t('system.default')}
                        </UI.Text>
                    </View>
                </Layout.Card>
            </View>

            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>模式与语言切换</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="切到 system 模式" onPress={onSetModeSystem} testID="i18n-btn-mode-system" />
                        <UI.Button title="切到 fixed 模式" variant="outline" onPress={onSetModeFixed} testID="i18n-btn-mode-fixed" />
                    </View>
                    <View style={[styles.row, { marginTop: 8 }]}>
                        <UI.Button title="设为 zh-CN" onPress={onSetTagZhCN} testID="i18n-btn-set-zh-cn" />
                        <UI.Button title="设为 en-US" onPress={onSetTagEnUS} testID="i18n-btn-set-en-us" />
                        <UI.Button title="设为 ar-SA（RTL）" onPress={onSetTagArSA} testID="i18n-btn-set-ar-sa" />
                        <UI.Button title="设为 zh-Hans（别名）" onPress={onSetTagAliasZhHans} testID="i18n-btn-set-zh-hans" />
                        <UI.Button title="恢复系统语言" variant="outline" onPress={onRestoreSystemTag} testID="i18n-btn-set-null-system" />
                    </View>
                    <UI.Text variant="caption" color="subtext" mt={8}>
                        说明：设置 tag 后若 mode≠fixed 会自动切到 fixed；zh-Hans 会映射为 zh-CN。
                    </UI.Text>
                </Layout.Card>
            </View>

            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>覆盖与重置（updateOverrides / resetOverrides）</UI.Text>
                    <UI.Text children={'覆盖键（如：welcome / common.ok）'} />
                    <UI.Input
                        value={overrideKey}
                        onChangeText={setOverrideKey}
                        placeholder="例如：welcome"
                        testID="i18n-input-override-key"
                    />
                    <UI.Text children={'覆盖值'} />
                    <UI.Input
                        value={overrideValue}
                        onChangeText={setOverrideValue}
                        placeholder="输入覆盖文案"
                        testID="i18n-input-override-val"
                    />
                    <View style={[styles.row, { marginTop: 8 }]}>
                        <UI.Button title="应用覆盖" onPress={onApplyOverride} testID="i18n-btn-apply-override" />
                        <UI.Button title="重置覆盖" variant="outline" onPress={onResetOverrides} testID="i18n-btn-reset-override" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>当前覆盖结果</UI.Text>
                        <UI.Text variant="body2" color="text" testID="i18n-text-override-result">
                            {overrideKey.trim() ? `${overrideKey}：${t(overrideKey.trim(), { name: nameInput })}` : '（未指定键）'}
                        </UI.Text>
                    </View>
                </Layout.Card>
            </View>

            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>RTL 对齐示例</UI.Text>
                    <UI.Text variant="caption" color="subtext" mb={8}>切到 ar-SA 查看行内顺序变化</UI.Text>
                    <View style={[styles.row, { flexDirection: rtl ? 'row-reverse' : 'row' }]} testID="i18n-rtl-demo">
                        <View style={[styles.rtlBox, { backgroundColor: colors.surface }]}><UI.Text>Box A</UI.Text></View>
                        <View style={[styles.rtlBox, { backgroundColor: colors.surface }]}><UI.Text>Box B</UI.Text></View>
                        <View style={[styles.rtlBox, { backgroundColor: colors.surface }]}><UI.Text>Box C</UI.Text></View>
                    </View>
                </Layout.Card>
            </View>
        </Layout.Page>
    );
};

export default LocalizationTestScreen;